using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text.Json;
using System.Windows.Forms;
using Work.Domain;
using Work.API.Dtos;

namespace WinFormsApp1
{
    public partial class DoctorWorkbenchForm : Form
    {
        private const string ApiBaseUrl = "http://localhost:5044";
        private readonly HttpClient _httpClient;
        private readonly JsonSerializerOptions _jsonOptions;

        public DoctorWorkbenchForm()
        {
            InitializeComponent();
            _httpClient = new HttpClient { BaseAddress = new Uri(ApiBaseUrl) };
            _jsonOptions = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
            InitializeComboBoxes();
            LoadAppointments(); // Load all appointments on startup
        }

        private void InitializeComboBoxes()
        {
            // Populate Department ComboBox
            cmbDepartment.Items.Clear();
            foreach (var name in Enum.GetNames(typeof(Departmentsel)))
            {
                cmbDepartment.Items.Add(name);
            }
            cmbDepartment.Items.Insert(0, "所有科室"); // Add an "All" option
            cmbDepartment.SelectedIndex = 0;

            // Populate Doctor ComboBox (initially empty, will be filled based on department)
            cmbDoctor.Items.Insert(0, "所有医生");
            cmbDoctor.SelectedIndex = 0;

            // Register event for department change to update doctors
            cmbDepartment.SelectedIndexChanged += CmbDepartment_SelectedIndexChanged;
        }

        private async void CmbDepartment_SelectedIndexChanged(object? sender, EventArgs e)
        {
            cmbDoctor.Items.Clear();
            cmbDoctor.Items.Insert(0, "所有医生");
            cmbDoctor.SelectedIndex = 0;

            var selectedDept = cmbDepartment.SelectedItem?.ToString();
            if (selectedDept != "所有科室" && !string.IsNullOrEmpty(selectedDept))
            {
                // This part would ideally fetch doctors from an API based on department ID
                // For now, using the same dictionary logic as AppointmentForm
                var deptDoctorMap = new Dictionary<string, List<string>>
                {
                    ["心血管内科"] = new List<string> { "张叁叁", "赵强" },
                    ["骨科"] = new List<string> { "李偲偲", "孙丽华" },
                    ["妇产科"] = new List<string> { "姜稳稳", "钱芳" },
                    ["儿科"] = new List<string> { "贾樟柯", "刘娜" },
                    ["眼科"] = new List<string> { "王武武", "郑伟" },
                    ["口腔科"] = new List<string> { "周建国", "何敏" },
                    ["皮肤科"] = new List<string> { "吴明", "林晓燕" },
                    ["中医科"] = new List<string> { "陈俊杰", "徐国栋" },
                    ["急诊科"] = new List<string> { "黄志伟", "马静", "张叁叁" }
                };

                if (deptDoctorMap.ContainsKey(selectedDept))
                {
                    foreach (var doctor in deptDoctorMap[selectedDept])
                    {
                        cmbDoctor.Items.Add(doctor);
                    }
                }
            }
        }

        private async void LoadAppointments()
        {
            try
            {
                var queryParams = new List<string>();
                if (!string.IsNullOrWhiteSpace(txtCardNumber.Text))
                    queryParams.Add($"cardNumber={Uri.EscapeDataString(txtCardNumber.Text)}");
                if (!string.IsNullOrWhiteSpace(txtPatientName.Text))
                    queryParams.Add($"patientName={Uri.EscapeDataString(txtPatientName.Text)}");
                if (cmbDepartment.SelectedItem?.ToString() != "所有科室")
                    queryParams.Add($"department={Uri.EscapeDataString(cmbDepartment.SelectedItem?.ToString() ?? "")}");
                if (cmbDoctor.SelectedItem?.ToString() != "所有医生")
                    queryParams.Add($"doctorName={Uri.EscapeDataString(cmbDoctor.SelectedItem?.ToString() ?? "")}");
                
                // Add date range params
                queryParams.Add($"startDate={dtpStartDate.Value:yyyy-MM-dd}");
                queryParams.Add($"endDate={dtpEndDate.Value:yyyy-MM-dd}");

                var url = "api/Appointment/GetAppointments";
                if (queryParams.Any())
                {
                    url += "?" + string.Join("&", queryParams);
                }

                var response = await _httpClient.GetAsync(url);
                response.EnsureSuccessStatusCode();
                var json = await response.Content.ReadAsStringAsync();
                var apiResult = JsonSerializer.Deserialize<ApiResult<List<AppointmentListDto>>>(json, _jsonOptions);

                if (apiResult != null && apiResult.Code == 100 && apiResult.Data != null)
                {
                    dgvAppointments.DataSource = apiResult.Data;
                    
                    // Update record count
                    lblRecordCount.Text = $"共 {apiResult.Data.Count} 条记录";
                    
                    // Hide row header (row numbers)
                    dgvAppointments.RowHeadersVisible = false;
                    
                    // Hide unnecessary columns
                    if (dgvAppointments.Columns.Contains("PatientId"))
                        dgvAppointments.Columns["PatientId"].Visible = false;
                    
                    // Configure DataGridView columns for better display
                    if (dgvAppointments.Columns.Contains("AppintmentId"))
                    {
                        dgvAppointments.Columns["AppintmentId"].HeaderText = "预约ID";
                        dgvAppointments.Columns["AppintmentId"].Width = 70;
                        dgvAppointments.Columns["AppintmentId"].DisplayIndex = 0; // Show as first column
                    }
                    if (dgvAppointments.Columns.Contains("RegistrationNum"))
                    {
                        dgvAppointments.Columns["RegistrationNum"].HeaderText = "挂号单号";
                        dgvAppointments.Columns["RegistrationNum"].Width = 120;
                    }
                    if (dgvAppointments.Columns.Contains("CardNumber"))
                    {
                        dgvAppointments.Columns["CardNumber"].HeaderText = "卡号";
                        dgvAppointments.Columns["CardNumber"].Width = 110;
                    }
                    if (dgvAppointments.Columns.Contains("PatientName"))
                    {
                        dgvAppointments.Columns["PatientName"].HeaderText = "姓名";
                        dgvAppointments.Columns["PatientName"].Width = 80;
                    }
                    if (dgvAppointments.Columns.Contains("Gender"))
                    {
                        dgvAppointments.Columns["Gender"].HeaderText = "性别";
                        dgvAppointments.Columns["Gender"].Width = 50;
                        // Display "男" or "女" based on boolean value
                        dgvAppointments.Columns["Gender"].DefaultCellStyle.Format = "男;女";
                    }
                    if (dgvAppointments.Columns.Contains("Age"))
                    {
                        dgvAppointments.Columns["Age"].HeaderText = "年龄";
                        dgvAppointments.Columns["Age"].Width = 50;
                    }
                    if (dgvAppointments.Columns.Contains("Phone"))
                    {
                        dgvAppointments.Columns["Phone"].HeaderText = "电话";
                        dgvAppointments.Columns["Phone"].Width = 100;
                    }
                    if (dgvAppointments.Columns.Contains("Department"))
                    {
                        dgvAppointments.Columns["Department"].HeaderText = "科室";
                        dgvAppointments.Columns["Department"].Width = 90;
                    }
                    if (dgvAppointments.Columns.Contains("DoctorName"))
                    {
                        dgvAppointments.Columns["DoctorName"].HeaderText = "医生";
                        dgvAppointments.Columns["DoctorName"].Width = 80;
                    }
                    if (dgvAppointments.Columns.Contains("AppointmentType"))
                    {
                        dgvAppointments.Columns["AppointmentType"].HeaderText = "号类";
                        dgvAppointments.Columns["AppointmentType"].Width = 60;
                    }
                    if (dgvAppointments.Columns.Contains("VisitDate"))
                    {
                        dgvAppointments.Columns["VisitDate"].HeaderText = "就诊日期";
                        dgvAppointments.Columns["VisitDate"].Width = 140;
                        dgvAppointments.Columns["VisitDate"].DefaultCellStyle.Format = "yyyy-MM-dd HH:mm";
                    }
                    if (dgvAppointments.Columns.Contains("RecordStatus"))
                    {
                        dgvAppointments.Columns["RecordStatus"].HeaderText = "病历状态";
                        dgvAppointments.Columns["RecordStatus"].Width = 80;
                    }
                }
                else
                {
                    MessageBox.Show(apiResult?.Message ?? "查询失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    dgvAppointments.DataSource = null;
                    lblRecordCount.Text = "共 0 条记录";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"查询预约失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                lblRecordCount.Text = "共 0 条记录";
            }
        }

        private void btnQuery_Click(object? sender, EventArgs e)
        {
            LoadAppointments();
        }

        private void btnReset_Click(object? sender, EventArgs e)
        {
            txtCardNumber.Text = string.Empty;
            txtPatientName.Text = string.Empty;
            cmbDepartment.SelectedIndex = 0;
            cmbDoctor.SelectedIndex = 0;
            dtpStartDate.Value = DateTime.Now.AddDays(-30);
            dtpEndDate.Value = DateTime.Now.AddDays(30);
            LoadAppointments();
        }

        private void DoctorWorkbenchForm_Load(object? sender, EventArgs e)
        {
            // Initialize date pickers
            dtpStartDate.Value = DateTime.Now.AddDays(-30);
            dtpEndDate.Value = DateTime.Now.AddDays(30);
            LoadAppointments();
        }

        private void btnViewRecord_Click(object? sender, EventArgs e)
        {
            // View record is the same as write record, but the record will be read-only if completed
            btnWriteRecord_Click(sender, e);
        }

        private async void btnWriteRecord_Click(object? sender, EventArgs e)
        {
            if (dgvAppointments.SelectedRows.Count == 0)
            {
                MessageBox.Show("请选择一个预约记录来写病历。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            var selectedAppointment = dgvAppointments.SelectedRows[0].DataBoundItem as AppointmentListDto;
            if (selectedAppointment == null)
            {
                MessageBox.Show("无法获取选中的预约信息。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            // Check if a medical record already exists for this appointment
            var existingRecordResponse = await _httpClient.GetAsync($"api/MedicalRecord/GetByAppointmentId?appointmentId={selectedAppointment.AppintmentId}");
            var existingRecordJson = await existingRecordResponse.Content.ReadAsStringAsync();
            var existingRecordResult = JsonSerializer.Deserialize<ApiResult<MedicalRecordDto?>>(existingRecordJson, _jsonOptions);

            MedicalRecordDto? medicalRecordToEdit = null;
            if (existingRecordResult != null && existingRecordResult.Code == 100 && existingRecordResult.Data != null)
            {
                medicalRecordToEdit = existingRecordResult.Data;
            }

            // 直接打开病历编辑界面（无论是新建还是编辑，都允许修改）
            using (var medicalRecordForm = new MedicalRecordForm(selectedAppointment, medicalRecordToEdit))
            {
                if (medicalRecordForm.ShowDialog(this) == DialogResult.OK)
                {
                    LoadAppointments(); // Refresh the list after saving medical record
                }
            }
        }

        private async void btnPrescribe_Click(object? sender, EventArgs e)
        {
            if (dgvAppointments.SelectedRows.Count == 0)
            {
                MessageBox.Show("请选择一个预约记录来进行开药操作。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            var selectedAppointment = dgvAppointments.SelectedRows[0].DataBoundItem as AppointmentListDto;
            if (selectedAppointment == null)
            {
                MessageBox.Show("无法获取选中的预约信息。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            try
            {
                // 1. 检查病历是否存在且状态为"已完成"
                var recordResponse = await _httpClient.GetAsync($"api/MedicalRecord/GetByAppointmentId?appointmentId={selectedAppointment.AppintmentId}");
                recordResponse.EnsureSuccessStatusCode();
                var recordJson = await recordResponse.Content.ReadAsStringAsync();
                var recordResult = JsonSerializer.Deserialize<ApiResult<MedicalRecordDto?>>(recordJson, _jsonOptions);

                if (recordResult == null || recordResult.Code != 100)
                {
                    MessageBox.Show("无法获取病历信息，请稍后重试。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (recordResult.Data == null)
                {
                    MessageBox.Show("该预约还没有病历记录，请先完成病历书写。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                // 2. 检查病历状态是否为"已完成"
                if (recordResult.Data.Status != "已完成")
                {
                    MessageBox.Show($"病历状态为\"{recordResult.Data.Status ?? "未知"}\"，只有状态为\"已完成\"的病历才能开药。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                // 3. 打开开药窗口
                using (var prescriptionForm = new PrescriptionForm(selectedAppointment))
                {
                    if (prescriptionForm.ShowDialog(this) == DialogResult.OK)
                    {
                        MessageBox.Show("开药成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        // 可以刷新列表或显示提示信息
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"开药操作失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private class ApiResult<T>
        {
            public int Code { get; set; }
            public string? Message { get; set; }
            public T? Data { get; set; }
        }
    }
}
